package com.mdlib.helper.api.network;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.mdlib.helper.model.BaseResult;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by librabin on 16/10/9.
 */

public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private final Gson mGson;
    private final TypeAdapter<T> adapter;

    public JsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        mGson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        BaseResult br1 = mGson.fromJson(response, BaseResult.class);
        if (br1.code == 0) {
            MediaType mediaType = value.contentType();
            Charset charset = mediaType != null ? mediaType.charset(UTF_8) : UTF_8;
            ByteArrayInputStream bis = new ByteArrayInputStream(response.getBytes());
            InputStreamReader reader = new InputStreamReader(bis,charset);
            JsonReader jsonReader = mGson.newJsonReader(reader);
            try {
                return adapter.read(jsonReader);
            } catch (Exception e) {
                BaseResult br2 = new BaseResult(br1.code, br1.msg, null);
                String br2Str = mGson.toJson(br2);
                return adapter.fromJson(br2Str);
            } finally {
                value.close();
            }

        } else {

            String errorData = "";
            try {
                JSONObject errorObject = new JSONObject(response);
                errorData = errorObject.optString("data");
            } catch (Exception e) {

            }

            value.close();
//            throw new ApiException(br1.code, br1.msg, errorData);

            BaseResult br2 = new BaseResult(br1.code, br1.msg, errorData);
            String br2Str = mGson.toJson(br2);
            return adapter.fromJson(br2Str);


        }


    }
}